import CryptoJS from 'crypto-js';

interface AESUtil {
  genKey(length?: number): string;
  encrypt(plaintext: string | object, key: string): string;
  decrypt(ciphertext: string, key: string): string | object;
}

const aesUtil: AESUtil = {
  // 获取key
  genKey(length: number = 16): string {
    const random = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let str = '';
    for (let i = 0; i < length; i++) {
      str += random.charAt(Math.floor(Math.random() * random.length));
    }
    return str;
  },

  // 加密
  encrypt(plaintext: string | object, key: string): string {
    if (typeof plaintext === 'object') {
      // JSON.stringify
      plaintext = JSON.stringify(plaintext);
    }
    const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.toString();
  },

  // 解密
  decrypt(ciphertext: string, key: string): string | object {
    const decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    const decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
    if (decString.charAt(0) === '{' || decString.charAt(0) === '[') {
      // JSON.parse
      return JSON.parse(decString);
    }
    return decString;
  },
};

export default aesUtil;
